package com.betterwood.dragon.worms;

import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import com.microsoft.playwright.options.WaitUntilState;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JZT {
    // 九州通, 系统失效。
    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO JZT############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            // page.navigate(site.getSiteUrl());
            page.navigate("https://fb2.yyjzt.com/");
            page.click("text=登录");
            page.waitForTimeout(3500);
            page.click(".userTips1");
            // page.click(".userCheck");
            page.pause();

            page.click("[placeholder=\"请输入用户名/手机号\"]");
            page.fill("[placeholder=\"请输入用户名/手机号\"]", "kxtyyls"); // Press Enter

            page.click("[placeholder=\"请输入密码\"]"); // Fill input[name="password"]
            page.fill("[placeholder=\"请输入密码\"]", "kxt123456");
            page.click("text=记住登录信息");
            page.pause();

            // Press Enter
            // page.waitForNavigation(new
            // Page.WaitForNavigationOptions().setUrl("http://bh.ry600.com/_shop/index.shtml"),
            // () ->
            page.waitForNavigation(() -> {
                page.click("text=登 录");
            });
            // ---------------------

            contextState = context.storageState();
            // log.info(contextState);
            log.info("############END OF LOGIN TO JZT#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {
        log.info("#######################################");
        log.info("############START FETCH FROM JZT########");

        List<Result> res = getList(site, search);
        log.info("END OF fetch product");
        log.info("**************FOUND NEW PRODUCTS!!!******************");

        log.info(Integer.toString(res.size()));
        log.info("**************FOUND NEW PRODUCTS!!!******************");
        return res;
    }

    public static List<Result> getList(Site site, SearchDTO search) {

        List<Result> list = new ArrayList<>();
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));

            String storageState = site.getLoginInfo();

            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));

            // Open new page
            Page page = context.newPage();

            page.navigate("https://fds.yyjzt.com/");

            log.info("**********");
            log.info(search.getKeywordStr());
            log.info("**********");
            page.waitForTimeout(5000);
            page.click("[placeholder=\"请输入商品名称/拼音简称/厂家\"]");
            String pinyin = PinyinUtil.getFirstLetter(search.getKeywordStr(), "");
            log.info("PINYIN IS:");
            log.info(pinyin);
            page.fill("[placeholder=\"请输入商品名称/拼音简称/厂家\"]", pinyin);

            page.click("text=搜 索");

            page.waitForTimeout(4500);
            if (page.isVisible("#recommandDiv")) {
                log.info("JZT HAVE NO RESULTS");
                return list;
            }

            String content = page.innerHTML("#list_big_pic");
            // page.pause();
            // log.info(content);
            // page.pause();

            Document doc = Jsoup.parseBodyFragment(content);
            Element body = doc.body();

            Elements lis = body.getElementsByTag("li");

            if (lis.size() == 0) {
                log.info("JZT HAVE NO RESULTS");
                return list;
            }

            for (Element li : lis) {

                Element nameElement = li.getElementsByClass("u_goods_tit").first();

                Element aElement = nameElement.getElementsByTag("a").first();

                String pName = aElement.text();

                Element proElement = li.getElementsByClass("u_goods_com").first();

                Element makerElement = li.getElementsByClass("u_goods_com").get(1);

                String prop = proElement.text();

                String maker = makerElement.text();

                Element priceEle = li.getElementsByClass("memberPrice").first();

                String priceClean = priceEle.text();

                Double priceDouble = NumberUtil.isNumber(priceClean) ? Double.parseDouble(priceClean) : 0;

                // log.info("商品名是:" + pName);
                // log.info("商品规格是:" + prop);
                // log.info("制造商是:" + maker);
                // log.info("价格是:" + priceClean);
                // log.info("数字价格是:" + priceDouble.toString());

                String productName = StrUtil.concat(true, pName, prop, maker);

                Result re = new Result();
                re.setKeywordStr(search.getKeywordStr());
                re.setProductName(productName);
                re.setOrderUrl(site.getSiteUrl());
                re.setScanTime(TimeUtil.currentTime());
                re.setSearchId(search.getId());
                re.setSiteName("九州通");
                // // // // // // re.setSiteId("");
                re.setSiteNo("JZT");
                re.setScanPrice(priceClean);

                re.setPrice(priceDouble);
                re.setStatus(0);

                // // // // // resultDao.save(re);
                list.add(re);

            }

            log.info("JZT WORM SUCCESS");

        } catch (RuntimeException e) {
            e.printStackTrace();
            log.info("JZT WORM FAILED");
        }

        return list;
    }
}
